package com.book.service.impl;

import com.aliyun.oss.OSSClient;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.book.dao.BookDao;
import com.book.dao.BookPictureDao;
import com.book.entity.BookEntity;
import com.book.entity.BookPictureEntity;
import com.book.exception.GlobalException;
import com.book.service.BookService;
import com.book.utils.PageUtils;
import com.book.utils.Query;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;


@Service("bookService")
public class BookServiceImpl extends ServiceImpl<BookDao, BookEntity> implements BookService {

    @Resource
    private BookDao bookDao;

    @Resource
    private BookPictureDao pictureDao;

    @Value("${aliyun.endpoint}")
    private  String endpoint;

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String  accessKeySecret ;

    @Value("${aliyun.bucketName}")
    private String bucketName;


    @Override
    @Transactional
    public void saveBook(BookEntity book) {
        String[] detailPriPaths = book.getDetailPriPath();
        book.setSales(0);
        bookDao.insert(book);
        System.out.println("~~~~~~~~~~~~~~BookId:" + book.getId());
        if(detailPriPaths != null){
            for(String detailPriPath: detailPriPaths){
                pictureDao.insert(new BookPictureEntity(null,detailPriPath,book.getId()));
            }
        }

    }



    @Override
    public IPage<BookEntity> queryPage() {
        Page<BookEntity> page = new Page<>(0,12);
        QueryWrapper<BookEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("stock",0);
        IPage<BookEntity> bookEntityIPage = bookDao.selectPage(page, queryWrapper);
        return bookEntityIPage;
    }



    @Override
    public IPage<BookEntity> bookInfoPage(Integer currentPage, Integer limit,String bookName) {
        if(limit == null || limit <= 0){
            limit = 12;
        }
        if(currentPage == null || currentPage <= 0){
            currentPage = 0;
        }
        Page<BookEntity> page = new Page<>(currentPage,limit);
        QueryWrapper<BookEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("stock",0);
        if(!StringUtils.isEmpty(bookName) && !StringUtils.isEmpty(bookName.trim()))queryWrapper.like("name",bookName);
        IPage<BookEntity> bookEntityIPage = bookDao.selectPage(page, queryWrapper);
        return bookEntityIPage;
    }

    @Override
    public void updateBook(BookEntity book) {
        if (book == null){
            throw new GlobalException(500,"修改的图书信息不能为空！");
        }
        BookEntity bookEntity = bookDao.selectById(book.getId());
        book.setVersion(bookEntity.getVersion());
        book.setCreatetime(bookEntity.getCreatetime());
        bookDao.updateById(book);

    }

    @Override
    public String upload(MultipartFile file) {

        String uploadUrl = null;

        try {
            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId,
                    accessKeySecret);


            //获取上传文件流
            InputStream inputStream = file.getInputStream();

            //构建日期路径：avatar/2019/02/26/文件名
            String fileName = "";
            String dataPath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            fileName = fileName + dataPath + "/";
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = fileName + uuid;
            String originalFilename = file.getOriginalFilename();
            fileName = fileName + originalFilename;



            //文件上传至阿里云
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //获取url地址
            uploadUrl = "http://" + bucketName + "." + endpoint + "/" + fileName;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return uploadUrl;
    }



}